<template>
	<div class="commend">
		<div>
			<div class="pulldown-wrapper">
				<div v-show="beforePullDown">
					<span>Pull Down and refresh</span>
				</div>
				<div v-show="!beforePullDown">
					<div v-show="isPullingDown">
						<span>Loading...</span>
					</div>
					<div v-show="!isPullingDown">
						<span>Refresh success</span>
					</div>
				</div>
			</div>
			<div>
				<HomeListItem 
					v-for="(v, i) in list" 
					:key="i" 
					:title="v.title" 
					:urls="v.urls" 
					:auth="v.auth"
					:createTime="v.createTime" 
					:count="v.count" 
					:type="v.type" 
					@click="$router.push('/detail/'+ v.id)"
				/>
			</div>
			<h3 v-if="finish">{{ errorMessage }}</h3>
			<h3 v-else>{{ loading ? '加载更多数据中...' : '' }}</h3>
		</div>
	</div>
</template>

<script lang="ts" setup>
import HomeListItem from '@/components/homeListItem/indexView.vue'
import axios from 'axios'
import { onMounted, ref } from 'vue';
import BetterScroll from 'better-scroll'

interface ListItem {
	title: string,
	urls: string[],
	"type": 'a' | 'b' | 'c' | 'd'
	"auth": string,
	"count": number,
	createTime: string,
	'id': string
}

const list = ref<ListItem[]>([]);
const loading = ref(false)
const finish = ref(false)
const errorMessage = ref('')
const beforePullDown = ref(true)
const isPullingDown = ref(false)

const pageCode = ref(1);
const getList = async () => {
	const resp = await axios.get('/api/list', { params: { pageCode: pageCode.value } });
	const { code, data, message } = resp.data;
	if (code === 200) {
		list.value = list.value.concat(resp.data.data);
		pageCode.value++
	} else {
		finish.value = true;
		errorMessage.value = message
	}
}


onMounted(() => {
	getList()
	// 页面准备就绪 初始化bs
	const bs = new BetterScroll('.commend', {
		observeDOM: true, // 开启 observe-dom 插件
		observeImage: true, // 开启 observe-image 插件
		pullUpLoad: true, // 上拉加载
		pullDownRefresh: true, // 下拉刷新
		click: true
	})

	bs.on('pullingUp', async () => {
		loading.value = true
		await new Promise((resolve) => setTimeout(resolve, 2000))
		await getList()
		bs.finishPullUp()
		loading.value = false
	})

	bs.on('pullingDown', async () => {
      beforePullDown.value= false
      isPullingDown.value = true
			list.value = []
			pageCode.value = 1
      await getList()
      isPullingDown.value = false
      bs.finishPullDown()
	})

})

</script>

<style scoped>
.commend {
	overflow: hidden;
	height: 100%;
}

h3 {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 46px;
}



.pulldown-wrapper {
	position:absolute;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
  transform: translateY(-100%) translateZ(0);
  text-align: center;
  color: #999;
	z-index: 10;
	/* top: -100%; */
}
  
</style>